/*
	author:zsb1987@foxmail.com
	date:2013-08-22
	version:v1.0.0

	@description:


*/
/**
 util类
*/
(function($,w){
	w.gUtils = w.gUtils || {};
	var utils = w.gUtils;

	$.extend(utils,{
			 /** 渲染简单模板
			  * @param template 模板
			  * @param data 数据
			  * */
		 fRenderTemplate:function(template,data){
			var content='';
			if(data instanceof Array){
				for(var i=0;i<data.length;i++){
					content+=gUtils.renderTemplate(template,data[i]);
				}
			}else{
				var t=template;
				for(var attr in data){
					var value=data[attr];
					if(value==null){
						value='';
					}
					t=t.replace(new RegExp("@{"+attr+"}","gm"),value);
				}
				content+=t;
			}
			return content;
		 },
		/**
		 *    弹出确认框 操作成功刷新列表，操作失败提示消息
		 **/
		fConfirmAndRefreshList:function(config) {
			gDialog.fConfirm(config.title, config.info, function(rs) {
				if(!rs){
					return;
				}

	            jQuery.ajax({
	    			url: config.url,
	    			type:'post',
	    			dataType: "json",
	    			data: config.param,
	    			success: function(data, ts) {
						gDialog.fClose();
						if(data['result']) {
								if(data['message']!=null & data['message']!=''){
									message_box.show(data['message'],'success');
								}
								queryList();
						 }else{
							var sMessage=data['message'];
							if(sMessage==null){
								sMessage='处理异常，请联系管理员！';
							}
							gDialog.fAlert(sMessage);
						 }
					}
				});
			});
		},
		/**
		 *
		 * @param param 表单参数
		 * @param validateSet 验证规则
		 * @param url URL
		 * @param successHandler 操作成功处理
		 * @param errorHandler 操作失败处理
		 */
		fSubmitForm: function(param, validateSet, url, successHandler, errorHandler) {
			if (form.validate(validateSet)) {
				$.ajax({
					url: url,
					type:'post',
					dataType: "json",
					data: param,
					success: function(data, ts) {
						gUtils.fProcessResult(data, successHandler, errorHandler);
					},
					beforeSend: function() {
						//$('.btn_submit').attr('disabled', true);
					}
				});
			}
		},
		fProcessResult: function(data, successHandler, errorHandler) {
			if (data) {
				if (data['result'] && data['result'] == true) {
					successHandler.call(this,data);
				} else {
					if (errorHandler) {
						errorHandler.call(this,data);
					} else {
						var sMessage=data['message'];
				 		if(sMessage==null){
							sMessage='处理异常，请联系管理员！';
						}
				 		gDialog.fAlert(sMessage);
					}
					//$('.btn_submit').attr('disabled', false);
				}
			}
		},
		fGetIFrame: function(url,id, param) {
			var jFrame=$("#"+id);
			if(jFrame.length<1){
				jFrame=$('iframe[name='+id+']');
			}
			if(jFrame.length>0){
				jFrame.attr("src",url)
			}
		},
		/** 获取主内容*/
		fGetBody: function(url, param,loadingMsg) {
			this.fGetHtml(url,'main_content' ,param,loadingMsg);
		},
		fGetHtml: function(url, id, param,loadingMsg) {
			var jContainer=$("#"+id);
			var timeFlag=(new Date()).getTime();
			jContainer.data('timeFlag',timeFlag);
			$.ajax({
				url:  url,
				dataType: "html",
				type:'post',
				data: param,
				success: function(data, textStatus) {
					var newTimeFlag=jContainer.data('timeFlag');
					if(timeFlag<newTimeFlag){
						//console.log('已经被新的内容更新，丢弃');
						return ;
					}
					jContainer.html(data);
				},
				beforeSend: function() {
					if(loadingMsg!=null &&loadingMsg!=false){
						gUtils.fLoading(id,loadingMsg);
					}
				}
			});
		},
		fLoading: function(id,loadingMsg){
			if(loadingMsg==true){
				loadingMsg='页面加载中，请稍候...';
			}
			$("#"+id).html('<div id="loading" class="data_loading">'+loadingMsg+'</div>');
		},
		fPageSize:function(methodName,dom,event){
			var $this=$(dom);
			var value=$this.val();
			value=value.replace(/[^\d]/g,'');
			$this.val(value);
			//解决浏览器之间的差异问题
			var keyCode=event.keyCode ? event.keyCode:(event.which?event.which:event.charCode);
			if(keyCode!=13){
				return ;
			}
			if(isNaN(value)){
				return;
			}
			var pageFun=eval(methodName);
			if(pageFun!=null){
				pageFun(1,value);
			}

		},
		fPostForm:function(url,param,target){
			target=target?target:'_blank';
			var _jForm = $("<form></form>",{
                            'id':'tempForm',
                            'method':'post',
                            'action':url,
                            'target':target,
                            'style':'display:none'
                            }).appendTo($("body"));


    		for(var attr in param){
    			var value=param[attr];
    			if(value!=null&&value!=''){
    				_jForm.append($("<input>",{'type':'hidden','name':attr,'value':value}));
    			}
    		}

    		//触发提交事件
            _jForm.trigger("submit");
            //表单删除
          	 _jForm.remove();
		},
		/**
		 * 更新导航
		 *
		 * @param id
		 * @param text
		 * @param url
		 */
		fUpdateNav : function(flag, id, text, url) {
			if (id == null) return;

			if (text!=null&&text!='') {
				var template='';
				var datas={'menuId':id,'menuName':text,'menuUrl':url};
				if(url==null||url==''){
					template='<li id="@{menuId}"><a href="javascript:;">@{menuName}</a> <span class="divider">/</span></li>';
				}else{
					template='<li id="@{menuId}"><a href="javascript:;" onclick="gUtils.fGotoNavLink(\'@{menuUrl}\',\'@{menuId}\')">@{menuName}</a> <span class="divider">/</span></li>';
				}
				var content=this.fRenderTemplate(template,datas);
				if(flag){
					$('#crumbs').html(content);
				}else{
					$('#crumbs').append(content);
				}
			}else{
				$('#' + id).remove();
			}
		},

		/**
		 * 跳转到指定页面，同时删除该导航后面的选项
		 */
		fGotoNavLink : function(url,id){
			var next=$("#"+id).next();
			if(next.length>0){
				$(next).remove();
			}
			this.fGetBody(url);
		}
	});
})(jQuery,window);
!function ($) {

	"use strict"; // jshint ;_;

	/* MODAL MANAGER CLASS DEFINITION
	* ====================== */

	var ModalManager = function (element, options) {
		this.init(element, options);
	};


	ModalManager.prototype = {

		constructor: ModalManager,

		init: function (element, options) {
			this.$element = $(element);
			this.options = $.extend({}, $.fn.modalmanager.defaults, this.$element.data(), typeof options == 'object' && options);
			this.stack = [];
			this.backdropCount = 0;
		},
		appendModal: function (modal) {
			this.stack.push(modal);
			var that = this;

			var options=modal.options;
			//binding modalmanager
			modal.$element.data('modalmanager',that);
			if($.fn.draggable){
				var dragConfig=$.extend({handle:'.drag-handle',cursor:'move',scroll:false,containment:'window'},options.dragConfig);
				if(modal.$element.find(dragConfig.handle).length>0){
					modal.$element.draggable(dragConfig);
				}
			}

			modal.$element.on('shown.bs.modal',targetIsSelf( function (e) {
				//show action
			}));

			modal.$element.on('hidden.bs.modal', targetIsSelf(function (e) {
				var reuse=modal.$element.data('reuse');
				if(reuse!=null && !reuse){
					that.removeModal(modal);
				}
			}));
		},
		hasOpenModal: function () {
			for (var i = 0; i < this.stack.length; i++){
				if (this.stack[i].isShown) return true;
			}

			return false;
		},

		removeModal: function (modal) {
			this.stack.splice(this.getIndexOfModal(modal), 1);
			modal.$element.off('.modalmanager');
			modal.$element.remove();
		},

		getModalAt: function (index) {
			return this.stack[index];
		},

		getIndexOfModal: function (modal) {
			for (var i = 0; i < this.stack.length; i++){
				if (modal === this.stack[i]) return i;
			}
		},
		//add by zhangshibin ,to close the top modal
		getTopModal: function(){
			var topModal;
			for (var i = 0; i < this.stack.length; i++){
				if (this.stack[i].isShown) {
					topModal = this.stack[i];
				}
			}
			return topModal;
		}
	};

	/* PRIVATE METHODS
	* ======================= */
	// make sure the event target is the modal itself in order to prevent
	// other components such as tabsfrom triggering the modal manager.
	// if Boostsrap namespaced events, this would not be needed.
	function targetIsSelf(callback){
		return function (e) {
			if (this === e.target){
				return callback.apply(this, arguments);
			}
		}
	}


	/* MODAL MANAGER PLUGIN DEFINITION
	* ======================= */

	$.fn.modalmanager = function (option, args) {
		return this.each(function () {
			var $this = $(this),
				data = $this.data('modalmanager');

			if (!data) $this.data('modalmanager', (data = new ModalManager(this, option)));
			if (typeof option === 'string') data[option].apply(data, [].concat(args));
		})
	};

	$.fn.modalmanager.defaults = {
		backdropLimit: 999,
		resize: true,
		spinner: '<div class="loading-spinner fade" style="width: 200px; margin-left: -100px;"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>'
	};

	$.fn.modalmanager.Constructor = ModalManager


}(jQuery);

/*
	dialog弹出层
*/
(function($,w){
	w.gDialog = w.gDialog || {};
	var dialog = w.gDialog;
	var modalStart='<div class="modal fade" tabindex="-1" role="dialog"  aria-hidden="true" data-backdrop="static" id="@{modalId}">'+
		'<div class="modal-dialog" style="width:@{width}px;"> <div class="modal-content">';
	var modalEnd='</div></div>';
	var headTemplate='<div class="modal-header">'+
				'<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>'+
				'<h4 class="modal-title">@{title}</h4> </div>';


	var alertTemplate='<div class="modal-header"><h4 class="modal-title">@{title}</h4> </div><div class="modal-body">'+
	'<p>@{msgContent}</p></div>  <div class="modal-footer"><button role="button" class="btn btn-primary JConfirmBtn">确定</button></div>';

	var confirmTemplate='<div class="modal-header"><h4 class="modal-title">@{title}</h4> </div><div class="modal-body">'+
	'<p>@{msgContent}</p></div>  <div class="modal-footer"><button role="button" class="btn btn-success JConfirmBtn">确定</button>'+
	'<button role="button" class="btn btn-default JCancelBtn">取消</button></div>';

	var promptTemplate='<div class="modal-header"><h4 class="modal-title">@{title}</h4></div><div class="modal-body">'+
	'<p>@{msgContent}</p><input type="text" class="input-xxlarge JPromptInput" value="@{defaultVal}" placeholder="请输入..."/></div>  <div class="modal-footer"><a role="button" class="btn btn-success JConfirmBtn">确定</a>'+
	'<a role="button" class="btn btn-default JCancelBtn">取消</a></div>';

	$.extend(dialog,{
		fCreate:function(config){
			if(!config) return;
			if(!config.modalId){
				config.modalId=this.fGenModalId();
			}
			var modalContent=modalStart;
			//if has title,then render head
			if(config.title){
				modalContent+=headTemplate;
			}
			modalContent+=modalEnd;
			var modalContent=gUtils.fRenderTemplate(modalContent,config);
			var $modalContent=$(modalContent).appendTo('body');

			//can not reuse
			$modalContent.data('reuse',false);
			if(config.url && config.url!=''){
					$.ajax({
					url : config.url,
					dataType : 'html',
					cache:false,
					async:false,
					data:config.param || "",
					success : function(data,textStatus){
						$modalContent.find('.modal-content').append(data);
					}
				});
			}else if(config.content){
			  $modalContent.find('.modal-content').append(config.content);
			}
			config.dragConfig=$.extend({handle:'.modal-header'},config.dragConfig);
			var modalConfig=$.extend({
					keyboard: false,
					show:false,
					reuse:false
				},config);

			var width=config['width'];
			if(width){
				modalConfig['width']=width;
			}
			$modalContent.modal(modalConfig);

			var modal= $modalContent.data('bs.modal');
			this.appendToModalManager(modal,config);
			return modal;
		},
		appendToModalManager: function(modal,options){
				var manager =$('body').data('modalmanager');
				if(!manager){
					manager=$('body').modalmanager().data('modalmanager');
				}

			manager.appendModal(modal);
		},
		fClose:function(id){
		 var modalManager=$('body').modalmanager().data('modalmanager');
			if(modalManager!=null){
				if(modalManager.hasOpenModal()){
					modalManager.getTopModal().hide();
				}
			}
		},



		fAlert:function(msg,callback){
			var data={title:'警告',msgContent:msg};
			var alertContent=gUtils.fRenderTemplate(alertTemplate,data);
			var config={content:alertContent,width:600};
			var modal=this.fCreate(config);
			modal.$element.find(".JConfirmBtn").click(function(){
				modal.hide();
				if(callback){
					callback();
				}
			});
			modal.show();
		},
		fConfirm:function(title,content,callback){
			var data={title:title,msgContent:content};
			var confirmContent=gUtils.fRenderTemplate(confirmTemplate,data);
			var config={content:confirmContent,width:600};
			var modal=this.fCreate(config);
			modal.$element.find(".JConfirmBtn").click(function(){
				modal.hide();
				if(callback){
					callback(true);
				}
			});
			modal.$element.find(".JCancelBtn").click(function(){
				modal.hide();
				if(callback){
					callback(false);
				}
			});
			modal.show();
		},
		fPrompt:function(title,content,defaultVal,callback){
			var data={'title':title,'msgContent':content,'defaultVal':defaultVal};
			var confirmContent=gUtils.fRenderTemplate(promptTemplate,data);
			var config={content:confirmContent,width:600};
			var modal=this.fCreate(config);
			modal.$element.find(".JConfirmBtn").click(function(){
				modal.hide();
				if(callback){
					var input=modal.$element.find(".JPromptInput").val();
					callback(input);
				}
			});
			modal.$element.find(".JCancelBtn").click(function(){
				modal.hide();
				if(callback){
					callback(null);
				}
			});
			modal.show();
		},
		fGenModalId:function(){
			return 'modal-'+new Date().getTime();
		}
	});

	 /* MODAL DATA-API
	  * ============== */

	  $(document).on('show.bs.modal', 'div.modal', function (e) {
		var $this = $(this);
		var modal=$this.data('bs.modal');
		var modalmanager=$this.data('modalmanager');
		if(!modalmanager){
			gDialog.appendToModalManager(modal);
			e.preventDefault();
			modal.show();
		}
	  });

})(jQuery,window);

 /**
  * This tiny script just helps us demonstrate
  * what the various example callbacks are doing
  */
 window.message_box = (function($) {
     "use strict";

     var elem,
         hideHandler,
         that = {};
     var alertStyles=['alert-info','alert-warning','alert-success','alert-danger'];

     that.init = function(options) {
     	if(elem){
     		return;
     	}
     	var html='<div id="message_box_info" class="alert alert-info alert-block" style="display:none;width:500px;position:fixed;'+
     	'left:50%;margin-left:-250px;top:30px;z-index:10000;"><button type="button" class="close">&times;</button>'+
     	'<span></span></div>';
     	$("body").append(html);
 		elem=$("#message_box_info");
 		elem.find('button.close').click(function(){
 			that.hide();
 		});
     };

     that.show = function(text,type,time) {
     	if(elem==null ||elem==undefined){
     		that.init();
     	}
     	 var alertClass='';
     	 if(type=='info'){
     		alertClass='alert-info';
     	 }else if(type=='success'){
     		alertClass='alert-success';
     	 }else if(type=='danger'){
     		alertClass='alert-danger';
     	 }else{
			alertClass='alert-warning';
		 }
     	 for ( var i = 0; i < alertStyles.length; i++) {
     		 elem.removeClass(alertStyles[i]);
     	 	}
     	 if(alertClass!=''){
     		elem.addClass(alertClass);
     	 }

         clearTimeout(hideHandler);
         elem.find("span").html(text);
         elem.fadeIn();
         if(time!=null || isNaN(time)){
         	time=4000;
         }

         hideHandler = setTimeout(function() {
             that.hide();
         }, time);
     };

     that.hide = function() {
         elem.fadeOut();
     };

     return that;
 }(jQuery));